<!-- 职位信息模板 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew
        :title="title"
        :breadCrumb="breadCrumb"
        :isShowBtn="true"
        show-back
      >
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <div>
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="请输入模板名称"
            search-button
            v-model="nameSearch"
            @press-enter="onSearch"
            @search="onSearch"
          >
            <template #button-icon>
              <icon-search />
            </template>
          </a-input-search>
        </div>
      </template>
      <template #right>
        <a-button type="primary" @click="add">新增模板</a-button>
        <a-button type="outline" @click="referenceVisible = true"
          >引用模板库</a-button
        >
        <a-button type="outline" @click="del(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn ref="tableRef" :tableData="templateData" :args="args">
      <a-table-column align="center" :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="职位说明书模板名称"
        dataIndex="name"
      >
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="职位类型"
        dataIndex="patternId"
      >
        <template #cell>
          {{ name }}
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="描述"
        dataIndex="remark"
      >
      </a-table-column>
      <!-- <a-table-column :width="150" title="创建人" dataIndex="remark">
        <template #cell="{ record }">
          {{ record.organizationTemplateModel.remark }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="创建时间" dataIndex="remark">
        <template #cell="{ record }">
          {{ record.organizationTemplateModel.remark }}
        </template>
      </a-table-column> -->
      <a-table-column
        align="center"
        :width="150"
        title="启用状态"
        dataIndex="enable"
      >
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="200"
        title="是否为默认模板"
        dataIndex="isShowDefault"
      >
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.isShowDefault"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column align="center" title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="26"
                @click="goPreview(record.id)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
  <NoticeTemplate
    ref="templateRef"
    :data="currRecord.data"
    :business-type="businessType"
    :validateFun="validateName"
    :add="addData"
    :tab-code-list="businessType"
    :edit="EditData"
    :fn="tableRef"
    :title="`${name}信息模板`"
  ></NoticeTemplate>
  <PreviewForm
    :data="currRecord.data"
    v-model:visible="previewFormVisible"
    sliceName="职位"
  >
  </PreviewForm>
  <TemplateReference
    v-model:visible="referenceVisible"
    :type="2"
    @referenceEmit="referenceEmit"
  />
</template>

<script lang="ts" setup>
import {
  GetPositionTemplate,
  PutPositionTemplateState,
  PostPositionTemplate,
  PutPositionTemplate,
  GetPositionTemplateDetail,
  DelPositionTemplate,
  CheckPositionTemplate,
  DelPositionTemplateCollections,
  DelPositionTemplateControls
} from '@/apis/management/organization/baseSetting/PositionSystem';
// import { GetControl } from '@/apis/management/base';
import { validateRules } from '@/utils/common';
import { useSetupFormStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import { Modal } from '@arco-design/web-vue';
import { PostReferencePositionTemplate } from '@/apis/management/organization/baseSetting';
import TemplateReference from '../../../Components/TemplateReference/index.vue';

const id = Number(useRoute().query.userId); // 组织类型id
const name = useRoute().query.name; // 组织类型名字
const breadCrumb = ['组织', '基础设置', '职位类型', `${name}信息模板`];
const title = `${name}职位说明书模板`;
const store = useSetupFormStore();
const businessType = ref([
  'SER_FUNCC13F8AAE489847FC866AA2732D3E88B7',
  'baseComponent'
]);
let tableRef = ref();
let templateRef = ref();
let nameSearch = ref(''); //名称搜索框

// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

// 储存当前数据
const currRecord: any = reactive({
  data: {}
  // positionTemplate: {},
  // level: 1,
  // positionInformation: [],
  // list: {
  //   positionTemplateModel: {
  //     positionCollectionModel: [
  //       {
  //         componentModel: []
  //       }
  //     ]
  //   }
  // }
});

const originData = ref(); // 储存原始数据

// 获取列表信息
const templateData = async (pageData?: any) => {
  const res: any = await GetPositionTemplate({
    // id: ID,
    ...pageData,
    ownerId: id,
    name: nameSearch.value,
    ownerType: 2
  });
  originData.value = cloneDeep(res.content);
  // temp.content = res.content[0].organizationTemplateModel;
  // deptName.value = res.content[0].patter.name;

  return Promise.resolve(res);
};

let referenceVisible = ref(false); // 模板引用弹窗
// 引用模板库
const referenceEmit = async (ids: [], arr: []) => {
  try {
    const tempName = arr.map((el: any) => el.name);
    if (
      originData.value.findIndex((el: any) => tempName.includes(el.name)) !== -1
    ) {
      Message.error('所引用的模板重复，请重新选择模板！');
      return;
    }
    await PostReferencePositionTemplate({
      ids,
      ownerId: id
    });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

let copyVisible = ref(false);
let currId = ref(0);
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

// // 复制
const copyEmit = async (formData: any) => {
  try {
    const record: any = await GetPositionTemplateDetail({ id: currId.value });
    delete record.id;
    delete record.createdAt;
    record.required = 2;
    record.name = formData.name;
    const template = cloneDeep(record);
    delete template.collectionModel;
    const templateId = await PostPositionTemplate({
      level: 1, // 默认传1
      template: {
        ...template,
        ownerId: id,
        ownerType: 2, // 职位默认传2
        isShowDefault: 2 // 复制的时候默认为不是默认模板
      }
    });
    const component = cloneDeep(record.collectionModel);
    for (let [index, item] of component.entries()) {
      delete item.id;
      const collection = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
        // pid: item2.pid || 0
      };
      const collectionId = await PostPositionTemplate({
        level: 2, // 第二层默认传2
        collection
      });
      // 将返回的collectionId赋值给每一个控件
      item.controlModel.forEach((item2: any, index3: number) => {
        item2.collectionId = collectionId;
        delete item2.id;
      });
      await PostPositionTemplate({
        level: 3, // 第三层传3
        control: item.controlModel
      });
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error) {
    console.log(error);
  }
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};

// 修改模板默认状态
const stateChange = async (record: any) => {
  try {
    // 获取更改状态之前的模板数据，并判断状态是否和当前的一样，如果一样则不能改成默认模板
    const temp = originData.value.find((item: any) => item.id === record.id);
    if (temp.isShowDefault === 1) Message.error('必须拥有一个默认模板！');
    else if (temp.enable !== 1)
      Message.error('不能将未启用的模板当作默认模板!');
    else
      await PutPositionTemplateState({
        ownerType: 2,
        id: record.id
      });
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除数据
const del = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find(
                  (item: any) => item.isShowDefault === 1
                )
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelPositionTemplate({
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                tableRef.value.loadData();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.isShowDefault === 1) Message.error('默认模板不能删除！');
      else {
        await DelPositionTemplate({
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        tableRef.value.loadData();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除数据
// const del = async (record: any) => {
//   try {
//     if (selectedList.value.length > 0) {
//       if (
//         selectedListData.value.find((item: any) => item.isShowDefault === 1)
//       ) {
//         Message.error('默认模板不能删除！');
//       } else {
//         await DelPositionTemplate({
//           ids: selectedList.value
//         });
//         tableRef.value.selectedList = [];
//         tableRef.value.loadData();
//       }
//     } else {
//       if (record.isShowDefault === 1) Message.error('默认模板不能删除！');
//       else {
//         await DelPositionTemplate({
//           ids: [record.id]
//         });
//       }
//       tableRef.value.loadData();
//     }
//   } catch (error: unknown) {
//     console.log(error);
//   }
// };

// 点击新增模板按钮
const add = () => {
  currRecord.data = {
    name: '',
    enable: 1,
    remark: ''
  };
  templateRef.value.fullScreen();
};

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currRecord.data.name && currRecord.data.id) {
      //
    } else {
      const data = {
        ownerType: 2, // 职位写死2
        ownerId: id,
        name
      };
      const res = await validateRules(CheckPositionTemplate, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let previewFormVisible = ref(false);

// 前往预览
const goPreview = async (id: number) => {
  try {
    const res: any = await GetPositionTemplateDetail({ id });
    currRecord.data.name = res.name;
    currRecord.data.details = res.collectionModel;
    previewFormVisible.value = true;
  } catch (error: unknown) {
    console.log(error);
  }
};
// 编辑 初始化控件数据
const goEdit = async (id: number, name?: string) => {
  const record: any = cloneDeep(await GetPositionTemplateDetail({ id }));
  record.seconds = record.collectionModel;
  delete record.collectionModel;
  if (name) {
    record.name = name;
    delete record.id;
  }
  record.seconds.forEach((ele: any) => {
    if (name) delete ele.id;
    ele.componentList = ele.controlModel;
    delete ele.componentModel;
    ele.componentList.forEach((item: any) => {
      const {
        ctlCnName,
        ctlEnName,
        ctlComponentType,
        ctlCode,
        ctlFieldName,
        ctlValue
      } = item;
      item.uuid = ctlCode;
      item.componentName = ctlCnName;
      item.componentType = ctlComponentType;
      item.code = ctlCode;
      item.fieldName = ctlFieldName;
      item.enName = ctlEnName;
      item.ctlValue = ctlValue;
      if (name) delete item.id;
    });
  });
  currRecord.data = cloneDeep(record);
  templateRef.value.fullScreen();
};
// 新增 模板新增函数
const addData = async (data: any, componentList: any) => {
  try {
    // 第一层，返回templateId赋值给第二层子集
    const templateId = await PostPositionTemplate({
      level: 1, // 默认传1
      template: {
        enable: data.enable,
        name: data.name,
        remark: data.remark,
        ownerId: id,
        ownerType: 2 // 职位默认传2
      }
    });
    let component = cloneDeep(componentList);
    // 用createdAt进行判断用户是否是复制再编辑模板
    if (component[0]?.createdAt) {
      component = [
        {
          componentList: component
        }
      ];
    }
    for (let [index, item] of component.entries()) {
      for (let item2 of item.componentList) {
        const collection = {
          cnName: item2.cnName,
          enName: item2.enName,
          subCode: item2.subCode,
          orderNo: item2.sort || index,
          templateId
          // pid: item2.pid || 0
        };
        const collectionId = await PostPositionTemplate({
          level: 2, // 第二层默认传2
          collection
        });
        // 将返回的collectionId赋值给每一个控件
        // item2.componentList.forEach((item2: any, index3: number) => {
        //   item2.collectionId = collectionId;
        // });
        const control = item2.componentList.map((item2: any) => {
          item2.collectionId = collectionId;
          let data;
          if (item2.subsetControlRel) {
            data = {
              ...item2,
              ...item2.subsetControlRel
              // ctlValue: item2?.ctlValue ? item2.ctlValue : ''
            };
          } else {
            data = {
              ...item2
              // ctlValue: item2?.ctlValue ? item2.ctlValue : ''
            };
          }
          if (data.subsetControlRel) delete data.subsetControlRel;

          return data;
        });
        await PostPositionTemplate({
          level: 3, // 第三层传3
          control
        });
      }
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 新增 模板编辑函数
const EditData = async (data: any, componentList: any) => {
  try {
    const templateId = data.id;
    // 第一层，返回templateId赋值给第二层子集
    await PutPositionTemplate({
      level: 1, // 默认传1
      template: {
        ...data,
        ownerId: id,
        ownerType: 2 // 职位默认传2
      },
      funcTemplateType: 2 // 职位默认传2
    });

    // 删除子集
    if (store.getCollectionsIds.length > 0) {
      await DelPositionTemplateCollections({
        ids: store.getCollectionsIds
      });
      store.delCollectionsIds = [];
    }

    // 删除控件
    if (store.getControlIds.length > 0) {
      await DelPositionTemplateControls({
        ids: store.getControlIds
      });
      store.delControlIds = [];
    }

    const component = cloneDeep(componentList);

    // // 循环修改值的结构
    for (let [index, item] of component.entries()) {
      const collection: any = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
        // pid: item2.pid || 0
      };
      let collectionId = 0;
      if (item.id) {
        collection.id = item.id;
        await PutPositionTemplate({
          level: 2, // 第二层默认传2
          collection
        });
        collectionId = item.id;
      } else {
        collectionId = (await PostPositionTemplate({
          level: 2, // 第二层默认传2
          collection
        })) as number;
      }
      for (let item2 of item.componentList) {
        item2.collectionId = collectionId;
      }
      await PutPositionTemplate({
        level: 3, // 第三层传3
        control: item.componentList
      });
    }

    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 搜索框
const onSearch = () => {
  tableRef.value.loadData();
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
.contain {
  padding: 10px 20px;

  .header {
    display: flex;
    justify-content: space-between;
    &-front {
      position: relative;
      line-height: 30px;
    }
    margin-bottom: 20px;
  }
  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    .input {
      width: 320px;
    }
  }
  .enable::before {
    content: '';
    display: inline-block;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    position: relative;
    right: 3px;
    background-color: var(--enable);
  }
}
</style>
